// README
//
// There are two steps to adding a property:
//
// 1. Create a member variable to store your property
// 2. Add the get_ and set_ accessors for your property.
//
// Remember that both are case sensitive!
//

Type.registerNamespace('GridControl');

GridControl.TreeEventArgs = function() {
   
    GridControl.TreeEventArgs.initializeBase(this);

}

GridControl.TreeEventArgs.prototype = {
  
    serialise : function(eventName,arguments){
    /// <summary>
    /// Method used to prepare an event to be fired
    /// </summary>
    /// <param name="eventName" type="string">
    /// Name of the event to be fired
    /// </param>
    /// <param name="arguments" type="object">
    /// Object containing the parameters to be passed
    /// </param>
        return Sys.Serialization.JavaScriptSerializer.serialize(
                {
                    EventName: eventName,
                    Arguments: Sys.Serialization.JavaScriptSerializer.serialize
                        (arguments)
                });
    } 
}

GridControl.TreeEventArgs.registerClass('GridControl.TreeEventArgs', Sys.EventArgs);

GridControl.TreePaneBehavior = function(element) {

    GridControl.TreePaneBehavior.initializeBase(this, [element]);
   
    this._animate = true;
    this._containerScroll=true;
    this._enableDD=true;
    this._lines=true;
    this._singleExpand=true;
    this._Loader="";
    this._rootVisible=true;
}

GridControl.TreePaneBehavior.prototype = {

    initialize : function() {
        GridControl.TreePaneBehavior.callBaseMethod(this, 'initialize');
        var id=this.get_element().id;
    
        var myTree = new Ext.tree.TreePanel(id, {
            animate:this._animate, 
            enableDD:this._enableDD,
            containerScroll: this._containerScroll,
            lines:this._lines,
            rootVisible:this._rootVisible
        });
        
        if(this._CheckBoxTree){
                myTree.rootUIProvider= Ext.tree.CheckboxNodeUI;
		        myTree.selModel=new Ext.tree.CheckNodeMultiSelectionModel();   
		        
		        if(this._Loader!=null && this._Loader !=""){
                    myTree.loader= new Ext.tree.CustomUITreeLoader({
			            dataUrl:this._Loader,
			            baseAttr: {
				            uiProvider: Ext.tree.CheckboxNodeUI
			            }
		            })
                    
               }
               if(this._Loader==null || this._Loader ==""){
                    myTree.loader= new Ext.tree.CustomUITreeLoader({
			            dataUrl:location.href,
			            baseAttr: {
				            uiProvider: Ext.tree.CheckboxNodeUI
			            }
		            })
                   
               }
              		        
        }
        else{
               if(this._Loader!=null && this._Loader !=""){
               
                    myTree.loader=new  Ext.tree.TreeLoader({dataUrl:this._Loader});
               }
               if(this._Loader==null || this._Loader ==""){
                    myTree.loader=new  Ext.tree.TreeLoader({dataUrl:location.href});
               }
               if(this._WebServicePath !=null && this._WebServicePath !=""){
                   myTree.loader=new Ext.tree.WebServiceTreeLoader({_WebServicePath:this._WebServicePath,_WebServiceMethod:this._WebServiceMethod});
               }
       }
       this._Tree=myTree;
       
       var nodes=eval(this._TreeNodes);
  
       if(nodes){
            for(var i=0;i<nodes.length;i++){
                  
                    if(nodes[i].leaf){
                          //does't have any ajax children
                          tmpNode = new Ext.tree.TreeNode(nodes[i]);
                    }
                    else{
                        //has ajax children
                        tmpNode = new Ext.tree.AsyncTreeNode(nodes[i]);
                   }
                   
                   if(nodes[i].IsRoot|| nodes[i].parentNodeId==null){
                      
                       myTree.setRootNode(tmpNode);
                      
                       continue;
                    }
                    var pNode=myTree.getNodeById(nodes[i].parentNodeId);
                    if(pNode){
                        pNode.appendChild(tmpNode);
                        
                    }
                    
            }
       }
       myTree.render();
       myTree.getRootNode().expand();
       if(this._Editable){
         // add an inline editor for the nodes
               var ge = new Ext.tree.TreeEditor(myTree, {
                    allowBlank:false,
                    blankText:'A name is required',
                    selectOnFocus:true
                });
                myTree.Editor=ge;
                ge.on("complete",this.raiseNodeEdited,this);
       }
       this.Tree=myTree;
       myTree.on("move",this.raiseNodeMoved,this);
       myTree.on("click",this.raiseClicked,this);
       if(this._CheckBoxTree){
        myTree.on("check",this.raiseChecked,this);
       }
       if(this._ContextMenu !=""){
            this.BuildContextMenu();
            myTree.on('contextmenu', this.ShowMenu,this); 
       }
    },
   ShowMenu:function(node){
       this.selectedNode=node;
       this.oContextMenu.show(node.ui.getAnchor()); 
   },
   BuildContextMenu: function(){
     
          var MenuTmp=eval('('+this._ContextMenu+')');
          var extMenuItems=[];
          if(MenuTmp==null){
            return;
          }
          for(i=0; i < MenuTmp.Items.length;i++){
             var objTemp={};
             var tmpItem=MenuTmp.Items[i];
             objTemp.text=tmpItem.Text;
             objTemp.id= tmpItem.Id;
             
             if(tmpItem.OnClientClick !=null && tmpItem.OnClientClick !=""){
                objTemp.handler=eval(tmpItem.OnClientClick); 
                //objTemp.scope=this;
             }
            else{
                objTemp.handler=this.raiseMenuItemClicked;
                objTemp.scope=this;
             }
             extMenuItems.push(objTemp);
          }
          oContextMenu = new Ext.menu.Menu({items:extMenuItems});
                               
          this.oContextMenu=oContextMenu;
    },
    dispose : function() {
        // TODO: add your cleanup code here

        GridControl.TreePaneBehavior.callBaseMethod(this, 'dispose');
    },
    get_Tree:function(){
        return this.Tree;
    },
    get_animate : function() {
        return this._animate;
    },

    set_animate : function(value) {
        this._animate = value;
    },
    get_containerScroll:function(){
        return this._containerScroll;
    },
    set_containerScroll:function(value){
        this._containerScroll=value;
    },
    get_enableDD:function(){
        return this._enableDD;
    },
    set_enableDD:function(value){
        this._enableDD=value;
    },
    get_enableDrag:function(){
        return this._enableDrag;
    },
    set_enableDrag:function(value){
           this._enableDrag=value;
    },
    get_enableDrop:function(){
        return this._enableDrop;
    },
    set_enableDrop:function(value){
        this._enableDrop=value;
    },
    get_rootVisible:function(){
        return this._rootVisible;
    },
    set_rootVisible:function(value){
        this._rootVisible=value;
    },
    get_ddGroup:function(){
        return this._ddGroup;
    },
    set_ddGroup:function(value){
        this._ddGroup=value;
    },
    get_lines:function(){
        return this._lines;
    },
    set_lines:function(value){
        this._lines=value;
    },
    get_singleExpand:function(){
        return this._singleExpand;
    },
    set_singleExpand:function(value){
        this._singleExpand=value;
    },
    get_TreeNodes:function(){
        return this._TreeNodes;
    },
    set_TreeNodes:function(value){
        this._TreeNodes=value;
    },
     get_Loader:function(){
        return this._Loader;
    },
    set_Loader:function(value){
        this._Loader=value;
    },
    get_Tree:function(){
        return this._Tree;
    },
    set_ddAppendOnly:function(value){
        this.ddAppendOnly=value;
    },
    get_ddAppendOnly:function(){
        return this._ddAppendOnly;
    },
       //WebServiceMethod
    get_WebServiceMethod : function() {
        return this._WebServiceMethod;
    },

    set_WebServiceMethod: function(value) {
        this._WebServiceMethod= value;
    },
    //WebServicePath
    get_WebServicePath : function() {
        return this._WebServicePath;
    },

    set_WebServicePath: function(value) {
        this._WebServicePath= value;
    },
    get_Editable:function(){
        return this._Editable;
    },
    set_Editable:function(value){
        this._Editable=value;
    },
    get_autoPostBack:function(){
        return this._autoPostBack;
    },
    set_autoPostBack:function(value){
        this._autoPostBack=value;
    },
    get_CheckBoxTree:function(){
        return this._CheckBoxTree;
    },
    set_CheckBoxTree:function(value){
        this._CheckBoxTree=value;
    },
    get_ContextMenu:function(){
        return this._ContextMenu;
    },
    set_ContextMenu:function(value){
        this._ContextMenu=value;
    },
    invoke :function(callbackId, args, onComplete$delegate, context, onError$delegate ,async){
       
        if (this._autoPostBack) {                    
            __doPostBack(callbackId, args);
        }
        else {
            WebForm_DoCallback(callbackId, args, onComplete$delegate, context, onError$delegate, async);
        }        
    },
    // Events
    add_NodeMoved : function(handler) {
        this.get_events().addHandler("NodeMoved", handler);
    },
    onCallbackError :function(result, context){
    },
    remove_NodeMoved : function(handler) {
        this.get_events().removeHandler("NodeMoved", handler);
    },
    raiseMenuItemClicked:function(item){
        
        var node=this.selectedNode;
        var eventArgs = new GridControl.TreeEventArgs();
        var arguments= new Object();
        arguments.NodeSelected=this.encodeNode(node);
        arguments.MenuClicked=this.encodeNode(item);
        this.invoke(this.get_element().id, eventArgs.serialise("ContextMenuClicked",arguments), null, this, this.onCallbackError, true);
    },
    raiseNodeMoved: function(tree,node,oldparent,newparent) {
        
        var handler = this.get_events().getHandler("NodeMoved");
        var eventArgs = new GridControl.TreeEventArgs();
        var arguments= new Object();
        arguments.NodeMoved=this.encodeNode(node);
        arguments.OldParent=this.encodeNode(oldparent);
        arguments.NewParent=this.encodeNode(newparent);
        if (handler) {
            handler(this, eventArgs);
        }
        this.invoke(this.get_element().id, eventArgs.serialise("NodeMoved",arguments), null, this, this.onCallbackError, true);
    },
    raiseNodeEdited:function(editor,newValue,oldValue){
        var eventArgs = new GridControl.TreeEventArgs();
        var arguments= new Object();
        arguments.NodeRenamed=this.encodeNode(editor.editNode);
        arguments.NewValue=newValue
        this.invoke(this.get_element().id, eventArgs.serialise("NodeEdited",arguments), null, this, this.onCallbackError, true);
    },
    raiseClicked:function(node,evnt){
        var eventArgs = new GridControl.TreeEventArgs();
        var arguments= new Object();
        node.isChecked= node.checked;
        arguments.NodeClicked=this.encodeNode(node);
       
        this.invoke(this.get_element().id, eventArgs.serialise("NodeClicked",arguments), null, this, this.onCallbackError, true);
    },
    raiseChecked:function(node,state){
  
        var eventArgs = new GridControl.TreeEventArgs();
        var arguments= new Object();
        node.isChecked= state;
        arguments.NodeChecked= this.encodeNode(node);
        
        var eventArgs = new GridControl.TreeEventArgs();
        this.invoke(this.get_element().id, eventArgs.serialise("NodeChecked",arguments), null, this, this.onCallbackError, true); 
    },
    /*
        Node capable of being converted to json
    */
    encodeNode:function(node){
        var cleanObject= new Object();
        for(var p in node){
            if(typeof(node[p])!="function" && typeof(node[p])!="object"){
              cleanObject[p]= node[p];
            }
        }
        //cleanObject.checked=node.checked;
        return cleanObject;
    },
    /*
        Removes a node from the tree
    */
    removeNode:function(id){
        debugger;
        var node;
        node=this._Tree.getNodeById(id);
        if(node.parentNode){
            node.parentNode.removeChild(node);
        }
    }
    
}

GridControl.TreePaneBehavior.registerClass('GridControl.TreePaneBehavior', AjaxControlToolkit.BehaviorBase);
